import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { WatchlistMiniService } from "./../watchlist-mini.service";
import { WatchlistGroup } from "./../watchlist-mini.model";
import * as _ from "lodash";

@Component({
  selector: 'modal-addstock',
  templateUrl: 'modaladdstock.component.html',
  styleUrls: ['modaladdstock.component.less']
})
export class ModalAddStockComponent implements OnInit, OnDestroy {
  @Input() symbolSource: Observable<any>;
  @Output() onHide = new EventEmitter<any>();
  allGroups: WatchlistGroup[] = undefined;
  initCheckedList: string[];  // 已经包含了该自选股的分组id列表
  initUncheckedList: string[];  // 未包含该自选股的分组id列表
  symbol: string;
  name: string;
  symbolSubscription: Subscription;

  constructor(private wms: WatchlistMiniService) { }

  ngOnInit() {
    this.symbolSubscription = this.symbolSource.subscribe(data => {
      this.symbol = data["symbol"];
      this.name = data["name"];
      this.allGroups = [];
      this.initCheckedList = [];
      if (!this.wms || !this.wms.rawGroups) return;
      this.wms.rawGroups.map(g => {
        console.log('rawGroups map:', g, this.symbol, g.symbols.indexOf(this.symbol));
        let checked = g.symbols.indexOf(this.symbol) === -1 ? false : true;
        if (checked) {
          this.initCheckedList.push(g.id);
        }
        this.allGroups.push(_.merge({}, g, { checked }));
      });
      // console.log('allGroups:', this.allGroups);
      // console.log('initCheckedList:', this.initCheckedList);
    });
  }

  ngOnDestroy() {
    this.symbolSubscription ? this.symbolSubscription.unsubscribe() : null;
  }

  confirm() {
    // console.log('confirm symbol:', this.symbol);
    // 计算需要删除的分组
    this.allGroups.map(g => {
      // 新增关注
      if (g["checked"]) {
        if (this.initCheckedList.indexOf(g.id) === -1) {
          // console.log('confirm add to group:', g);
          this.wms.addGroupSymbols(g, [this.symbol]);
        }
      } else {
        // 取消关注
        if (this.initCheckedList.indexOf(g.id) !== -1) {
          // console.log('confirm delete from group:', g);
          this.wms.deleteGroupSymbols(g, [this.symbol]);
        }
      }
    });
    this.closeModal();
  }

  onClick(group) {
    console.log('click group:', group.name);
  }

  closeModal(e?) {
    if (e) {
      e.preventDefault();
    }
    this.onHide.emit(true);
  }
}